package com.hmy.uaa.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmy.uaa.bo.request.MenuRequest;
import com.hmy.uaa.bo.response.MenuResponse;
import com.hmy.uaa.bo.response.RoleMenuResponse;
import com.hmy.uaa.mapper.MenuMapper;
import com.hmy.uaa.po.Menu;
import com.hmy.uaa.po.RoleMenuRelation;
import com.hmy.common.exception.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 菜单管理
 */
@Service
@Slf4j
public class MenuService {

    @Autowired
    private MenuMapper menuMapper;


    @Autowired
    private RoleMenuRelationService roleMenuRelationService;

    /**
     * 菜单注册
     *
     * @param roleId
     */
    public List<MenuResponse> getMenuListByRoleId(Long roleId) {
        List<MenuResponse> list = menuMapper.getMenuListByRoleId(roleId);
        Map menuMap = new HashMap();

        List<MenuResponse> newList = new ArrayList<>();
        List<MenuResponse> childList = new ArrayList<>();
        MenuResponse tempMenuResponse = null;
        for (MenuResponse menuResponse : list) {

            if (menuResponse.getLevel() == 1) {

                if (Objects.nonNull(tempMenuResponse)) {

                    if (Objects.nonNull(childList)) {
                        tempMenuResponse.setChildren(childList);

                    }
                    newList.add(tempMenuResponse);


                }
                childList = new ArrayList<>();
                tempMenuResponse = menuResponse;

            } else if (menuResponse.getLevel() == 2 && Objects.nonNull(tempMenuResponse)) {
                childList.add(menuResponse);
            }
        }

        //设置最后一个父节点数据
        if (Objects.nonNull(tempMenuResponse)) {
            tempMenuResponse.setChildren(childList);
            newList.add(tempMenuResponse);
        }

        return newList;

    }

    /**
     * 新增菜单
     *
     * @param menuRequest 请求参数
     */
    public void save(MenuRequest menuRequest) {
        if (isExists(menuRequest)) {
            throw new ClientException("菜单名称已存在");
        }
        Menu menu = convertBean(menuRequest);
        menu.setCreateTime(LocalDateTime.now());
        menuMapper.insert(menu);
    }

    /**
     * 修改菜单
     *
     * @param MenuRequest 请求参数
     */
    public void update(MenuRequest MenuRequest) {

        if (isExists(MenuRequest)) {
            throw new ClientException("菜单名称已存在");
        }

        Menu menu = convertBean(MenuRequest);
        menu.setId(MenuRequest.getId());
        menu.setUpdateTime(LocalDateTime.now());
        menuMapper.updateById(menu);
    }

    /**
     * 删除菜单
     *
     * @param id 菜单id
     */
    public void delete(Long id, Long parentId) {

        //判断该菜单是否存在二级菜单
        Integer countMenu = menuMapper.count(id);
        if (countMenu > 1) {
            throw new ClientException("删除失败，该菜单有二级菜单");
        }

        //判断该菜单是否有绑定角色
        RoleMenuRelation roleMenuRelation = new RoleMenuRelation();
        roleMenuRelation.setMenuId(id);
        boolean isExistsRole = roleMenuRelationService.isBindMenu(roleMenuRelation);
        if (isExistsRole) {
            throw new ClientException("删除失败，该菜单有绑定角色");
        }


        //删除菜单
        LambdaQueryWrapper<Menu> roleWrapper = Wrappers.<Menu>lambdaQuery()
                .eq(Menu::getId, id);
        menuMapper.delete(roleWrapper);
    }

    /**
     * 查询菜单分页
     *
     * @param page 分页参数
     * @param name 角色名称
     * @return Page<Menu>
     */
    public Page<Menu> queryPage(Page<Menu> page, String name) {
        LambdaQueryWrapper<Menu> query = Wrappers.<Menu>lambdaQuery();

        if (Objects.nonNull(name)) {
            query.like(Menu::getName, name);
        }

        return menuMapper.selectPage(page, query);
    }

    /**
     * 根据角色查询菜单列表
     *
     * @param roleId 角色id
     * @return List<RoleMenuResponse> 返回数据
     */
    public List<RoleMenuResponse> queryList(Long roleId) {
        return roleMenuRelationService.queryRoleMenuList(roleId);
    }

    /**
     * 判断菜单信息是否存在
     *
     * @param menuRequest 请求参数
     * @return boolean true：存在；false：不存在
     */
    private boolean isExists(MenuRequest menuRequest) {
        LambdaQueryWrapper<Menu> queryWrapper = Wrappers.<Menu>lambdaQuery();
        if (Objects.nonNull(menuRequest.getTitle())) {
            queryWrapper.eq(Menu::getTitle, menuRequest.getTitle());
        }

        if (Objects.nonNull(menuRequest.getParentId())) {
            queryWrapper.eq(Menu::getParentId, menuRequest.getParentId());
        }
        return menuMapper.selectCount(queryWrapper) > 0;
    }

    /**
     * 转换bean
     *
     * @param menuRequest 请求参数
     * @return Menu 返回转换对象
     */
    private Menu convertBean(MenuRequest menuRequest) {
        Menu menu = new Menu();

        menu.setName(menuRequest.getName());
        menu.setLevel(menuRequest.getLevel());
        menu.setIcon(menuRequest.getIcon());
        menu.setParentId(menuRequest.getParentId());
        menu.setTitle(menuRequest.getTitle());
        menu.setSort(menuRequest.getSort());
        return menu;
    }


}
